# -*- coding: utf-8 -*-
import yaml
import os
import sys
import gc

from src.util.util import GetLog


log = GetLog("conf.log")
AFFFA="jv965720b239b8396b1b7df8b768c919e86e10f"
AFFFB="j7tuu65702w2x8d7"

def load_file(path):
    with open(path, 'r', encoding="utf-8") as f:
        res = yaml.safe_load(f.read())
    return res

confMap={}

# class Conf(object):
#     def __init__(self,base_data):
#         self.data={}
#         self.base_data=base_data
#         self.updateData("游戏线程大漠插件是否绑定",0)
#
#     def updateData(self,path,default="",default_split="."):
#         parts=path.split(default_split)
#         current=self.base_data
#         for part in parts:
#             if isinstance(current,dict):
#                 if part in current:
#                     current=current[part]
#                 else:
#                     current=default
#                     break
#             elif isinstance(current,list):
#                 try:
#                     index=int(part)
#                     current=current[index]
#                 except ValueError :
#                     log.error("%s 不能解析1" % path)
#                     current = default
#                     break
#                 except IndexError:
#                     log.error("%s 不能解析2" % path)
#                     current = default
#                     break
#         self.data[path]=current



def total_size(obj):
    """返回对象及其内部所有引用的对象的大小总和"""
    seen_ids = set()
    size = 0
    objects = [obj]
    while objects:
        need_to_search = []
        for obj in objects:
            if not id(obj) in seen_ids:
                seen_ids.add(id(obj))
                size += sys.getsizeof(obj)
                need_to_search.append(obj)
        objects = gc.get_referents(*need_to_search)
    return size






def mergeDate(data1,data2):
    if type(data2) in[list,str,int,float,bool] :
        return data2
    if type(data2) is dict:
        for k,v in data2.items():
            if k in data1.keys():
                data1[k]=mergeDate(data1[k],v)
            else:
                data1[k] = v
    return data1

def makeConf(n=0):
    publicData = load_file(r"conf\conf.yaml")
    class_name = "SDL_app"
    tittle = "Dota 2"
    if publicData["系统"]["启动模式"] == "沙盒":
        class_name = "Sandbox:%s:%s" % (publicData["系统"]["沙盒名称"], class_name)
        tittle = "[#] [%s] %s [#]" % (publicData["系统"]["沙盒名称"], tittle)
    publicData["dota2_class_name"] = class_name
    publicData["dota2_tittle"] = tittle
    if len(publicData["循环配置"]) == 0 or n == -1:
        del publicData["循环配置"]
        result = publicData
    else:
        files = os.listdir("conf/%s" % publicData["循环配置"])
        confs = [x for x in files if x.endswith(".yaml")]
        cycle_path = confs[n % len(confs)]
        cycle_data = load_file(r"conf/%s/%s" % (publicData["循环配置"], cycle_path))
        del publicData["循环配置"]
        cycle_data.pop("循环配置", None)
        result = mergeDate(publicData, cycle_data)

    result["是否需要重启"] = False
    if "注册码" not in result["系统"] or result["系统"]["注册码"] == "":
        result["系统"]["注册码"] = AFFFA
        result["系统"]["附加码"] = AFFFB
    return  result

def getConf(n=0):
    if n in confMap.keys():
        result  = confMap[n]
    else:
        result = makeConf(n)
        confMap[n] = result
    result["obj"] = {}
    total = total_size(result)
    result["memory"]=f"Total size of object including references: %s kb" % {total/1024}
    return result

if __name__ == '__main__':
    getConf()